// @ts-ignore
import type { Plugin } from 'vite'
// @ts-ignore
import path from 'path'
import { RouteObject } from 'react-router-dom'

import { generate, getAutoRouterJs } from './generate'
import { defaultOptions, Options } from './options'

// @ts-ignore
declare module 'virtual:auto-router' {
  export const routes: RouteObject[]
  export default routes;
}

// 虚拟模块名称
const virtualFibModuleId = 'virtual:auto-router'
// Vite 中约定对于虚拟模块，解析后的路径需要加上`\0`前缀
const resolvedFibVirtualModuleId = '\0' + virtualFibModuleId

export default function vitePluginAutoRouter(
  options?: Partial<Options>,
): Plugin {

  const resolvedOptions = { ...defaultOptions, ...options }

  return {
    name: 'vite-plugin-auto-react-router',
    version: '1.0.0',
    enforce: 'pre',
    configureServer(server) {
      if (resolvedOptions.watch && !resolvedOptions.enableVirtualRouter) {
        const listener = (file = '') => (file.includes(path.normalize(resolvedOptions.pageDir)) ? generate(resolvedOptions) : null)
        server.watcher.on('add', listener)
        server.watcher.on('change', listener)
        server.watcher.on('unlink', listener)
      }
    },
    buildStart() {
      if(!resolvedOptions.enableVirtualRouter){
        return generate(resolvedOptions)
      }
      return Promise.resolve()
    },
    resolveId(id: string) {
      if (id === virtualFibModuleId) {
        return resolvedFibVirtualModuleId
      }
    },
    load(id: string) {
      // 加载虚拟模块
      if (id === resolvedFibVirtualModuleId) {
        // 返回虚拟模块内容
        const autoRouterJs=getAutoRouterJs(resolvedOptions);
        return autoRouterJs;
      }
    },
  }
}
